package com.bz.xtcx.manager.controller;

import com.alibaba.fastjson.JSONArray;
import com.bz.xtcx.manager.entity.BusUserCheck;
import com.bz.xtcx.manager.entity.BusUserForm;
import com.bz.xtcx.manager.enums.CheckStatusEnum;
import com.bz.xtcx.manager.enums.UserTypeEnum;
import com.bz.xtcx.manager.service.ILibService;
import com.bz.xtcx.manager.utils.ExcelUtil;
import com.bz.xtcx.manager.utils.MyFileUtil;
import com.bz.xtcx.manager.utils.WzStrUtil;
import com.bz.xtcx.manager.vo.VoQuery;
import com.bz.xtcx.manager.vo.VoResponse;
import com.bz.xtcx.manager.vo.VoTaskSum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("lib")
public class LibController {
    
    @Autowired
    private ILibService libService;
    
    @Value("${file.tomcatPath}")
    private String tomcatPath;

    /**
     * 获取表格基础数据
     * @param type
     * @return
     */
    @GetMapping("getForm")
    public Object getUserForm(@RequestParam("type") int type){
        VoResponse voRes = new VoResponse();
        voRes.setData(libService.getUserForm(type));
        return voRes;
    }

    /**
     * 设置表格基础数据
     * @param form
     * @return
     */
    @PostMapping("setForm")
    public Object setUserForm(@RequestBody BusUserForm form){
        VoResponse voRes = new VoResponse();
        voRes = libService.setUserForm(form);
        return voRes;
    }
    
    /**
     * 用户 保存/提交加入社区信息
     * @param detail
     * @param isDraft
     * @return
     */
    @PostMapping("setUserDetail")
    public Object setUserDetail(@RequestBody String detail, @RequestParam(value="isDraft", required=false) boolean isDraft){
        VoResponse voRes = new VoResponse();
        if(isDraft) {
            voRes.setData(libService.saveFormHis(detail));
        }else {
            voRes = libService.setUserDetail(detail);
        }
        return voRes;
    }
    
    /**
     * 管理员 新增/更新资源库信息
     * @param form
     * @return
     */
    @PostMapping("addLib")
    public Object addLib(@RequestBody BusUserForm form){
        VoResponse voRes = new VoResponse();
        if(form.getFormType()<1 || form.getFormType()>4) {
            voRes.setFail(voRes);
            voRes.setMessage("类型错误");
            return voRes;
        }
        if(form.getCheckStatus()<-1 || form.getCheckStatus()>2) {
            voRes.setFail(voRes);
            voRes.setMessage("状态错误");
            return voRes;
        }
        voRes = libService.addLib(form);
        return voRes;
    }
    
    /**
     * 删除资源库信息
     * @return
     */
    @DeleteMapping("delLib")
    public Object delLib(@RequestParam("id") String id, @RequestParam("type") String type){
        VoResponse voRes = new VoResponse();
        libService.delLib(id, type);
        return voRes;
    }
    
    /**
     * 删除资源库表格信息
     * @return
     */
    @DeleteMapping("delLibForm")
    public Object delLibForm(@RequestParam("id") String id){
        VoResponse voRes = new VoResponse();
        libService.delForm(id);
        return voRes;
    }
    
    /**
     * 获取用户 在资源库中是否存在对应的信息
     * @return
     */
    @GetMapping("isInLibs")
    public Object isInLibs(){
        VoResponse voRes = libService.getLibsByUser();
        return voRes;
    }
    
    /**
     * 根据用户类别、名称和证件号查找资源库中是否存在对应的信息
     * @param name
     * @param code
     * @param userType
     * @return
     */
    @GetMapping("isInLib")
    public Object isInLib(@RequestParam("name") String name, @RequestParam("code") String code,@RequestParam("userType") int userType){
        VoResponse voRes = new VoResponse();
        voRes.setData(libService.getLibsByUser(userType, name, code));
        return voRes;
    }
    
    /**
     * 管理员获取注册用户信息
     * @param userId
     * @return
     */
    @GetMapping("getUserDetailByUserId")
    public Object getUserDetailById(@RequestParam("userId") String userId){
        VoResponse voRes = new VoResponse();
        voRes.setData(libService.getUserDetailById(userId));
        return voRes;
    }
    
    /**
     * 用户获取资源库信息
     * @param isDraft
     * @return
     */
    @GetMapping("getUserDetail")
    public Object getUserDetail(@RequestParam(value="isDraft", required=false) boolean isDraft){
//        VoResponse voRes = new VoResponse();
//        voRes.setData(libService.getUserDetail(isDraft));
        VoResponse voRes = libService.getUserDetail(isDraft);
        return voRes;
    }
    
    /**
     * 获取资源库待办任务汇总数据(管理员)
     * @return
     */
    @GetMapping("getSubmitLibSum")
    public Object getSubmitLibSum(){
        VoResponse voRes = new VoResponse();
        voRes.setData(libService.taskDoingSum());
        return voRes;
    }
    
    /**
     * 获取资源库待办任务（用户）
     * @return
     */
    @GetMapping("getSubmitLib")
    public Object getSubmitLib(){
        VoResponse voRes = new VoResponse();
        Map<String, List<VoTaskSum>> dbTask = new HashMap<String, List<VoTaskSum>>();
        dbTask.put("libsum", libService.taskDoing());
        dbTask.put("djfromsum", libService.taskDjFromerDoingSum());
        dbTask.put("djtargetsum", libService.taskDjTargeterDoingSum());
        voRes.setData(dbTask);
        return voRes;
    }
    
    /**
     * 管理员驳回用户完善信息
     * @param checkinfo
     * @return
     */
    @PostMapping("rejectUserDetail")
    public Object rejectUserDetail(@RequestBody BusUserCheck checkinfo){
        VoResponse voRes = new VoResponse();
        voRes = libService.rejectUserDetail(checkinfo.getFormId(), checkinfo.getInfo());
        return voRes;
    }
    
    /**
     * 查看审核历史信息
     * @param id
     * @return
     */
    @GetMapping("getCheckInfo")
    public Object getCheckInfo(@RequestParam("id") String id){
        VoResponse voRes = new VoResponse();
        voRes.setData(libService.getCheckInfo(id));
        return voRes;
    }
    
    /**
     * 管理员审核资源库信息
     * @param id
     * @return
     */
    @GetMapping("checkUserDetail")
    public Object checkUserDetail(@RequestParam("id") String id){
        VoResponse voRes = new VoResponse();
        voRes = libService.checkUserDetail(id);
        return voRes;
    }
    
    /**
     * 管理员审核资源库信息（批量）
     * @param ids
     * @return
     */
    @PostMapping("checkUserDetails")
    public Object checkUserDetail(@RequestBody List<String> ids){
        VoResponse voRes = new VoResponse();
        voRes = libService.checkUserDetail(ids);
        return voRes;
    }
    
    /**
     * 管理员上架架资源库信息
     * @param id
     * @return
     */
    @PutMapping("onUserDetail")
    public Object onUserDetail(@RequestParam("id") String id, @RequestParam("type") int type){
        VoResponse voRes = new VoResponse();
        voRes = libService.updateLibStatus(id, type, 1);
        return voRes;
    }
    
    /**
     * 管理员上架架资源库信息（批量）
     * @param ids
     * @param type
     * @return
     */
    @PutMapping("onUserDetails")
    public Object onUserDetail(@RequestBody List<String> ids, @RequestParam("type") int type){
        VoResponse voRes = new VoResponse();
        for(String id : ids) {
            voRes = libService.updateLibStatus(id, type, 1);
        }
        return voRes;
    }
    
    /**
     * 管理员下架资源库信息
     * @param id
     * @param type
     * @return
     */
    @PutMapping("offUserDetail")
    public Object offUserDetail(@RequestParam("id") String id, @RequestParam("type") int type){
        VoResponse voRes = new VoResponse();
        voRes = libService.updateLibStatus(id, type, 0);
        return voRes;
    }
    
    /**
     * 管理员下架资源库信息（批量）
     * @param ids
     * @param type
     * @return
     */
    @PutMapping("offUserDetails")
    public Object offUserDetail(@RequestBody List<String> ids, @RequestParam("type") int type){
        VoResponse voRes = new VoResponse();
        voRes = libService.offUserDetail(ids, type);
        return voRes;
    }
    
    /**
     * 管理员修改资源库信用
     * @param id
     * @return
     */
    @PutMapping("updateLibCreditLevel")
    public Object updateLibCreditLevel(@RequestParam("id") String id, @RequestParam("type") int type, @RequestParam("creditLevel") int creditLevel){
        VoResponse voRes = new VoResponse();
        voRes = libService.updateLibCreditLevel(id, type, creditLevel);
        return voRes;
    }
    
    @GetMapping("expert/page")
    public Object getAllExperts(@RequestParam("objName") String objName, @RequestParam("checkStatus") String checkStatus, 
            @RequestParam("creditLevel") String creditLevel, @RequestParam("status") String status,
            @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize,
            @RequestParam(value="orderBy",required=false)  String orderBy) {
        VoQuery lib = new VoQuery();
        lib.setObjName(objName);
        lib.setCheckStatus(checkStatus);
        lib.setCreditLevel(creditLevel);
        lib.setStatus(status);
        VoResponse voRes =  libService.getExpertPageByCondition(lib, pageNum, pageSize, orderBy);
        return voRes;
    }
    
    @GetMapping("college/page")
    public Object getAllColleges(@RequestParam("objName") String objName, @RequestParam("checkStatus") String checkStatus, 
            @RequestParam("creditLevel") String creditLevel, @RequestParam("status") String status,
            @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize,
            @RequestParam(value="orderBy",required=false)  String orderBy) {
        VoQuery lib = new VoQuery();
        lib.setObjName(objName);
        lib.setCheckStatus(checkStatus);
        lib.setCreditLevel(creditLevel);
        lib.setStatus(status);
        VoResponse voRes = libService.getCollegePageByCondition(lib, pageNum, pageSize, orderBy);
        return voRes;
    }
    
    @GetMapping("enterprise/page")
    public Object getAllEnterprises(@RequestParam("objName") String objName, @RequestParam("checkStatus") String checkStatus, 
            @RequestParam("creditLevel") String creditLevel, @RequestParam("status") String status,
            @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize,
            @RequestParam(value="orderBy",required=false)  String orderBy) {
        VoQuery lib = new VoQuery();
        lib.setObjName(objName);
        lib.setCheckStatus(checkStatus);
        lib.setCreditLevel(creditLevel);
        lib.setStatus(status);
        VoResponse voRes =  libService.getEnterprisePageByCondition(lib, pageNum, pageSize, orderBy);
        return voRes;
    }
    
    @GetMapping("services/page")
    public Object getAllServices(@RequestParam("objName") String objName, @RequestParam("checkStatus") String checkStatus, 
            @RequestParam("creditLevel") String creditLevel, @RequestParam("status") String status,
            @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize,
            @RequestParam(value="orderBy",required=false)  String orderBy) {
        VoQuery lib = new VoQuery();
        lib.setObjName(objName);
        lib.setCheckStatus(checkStatus);
        lib.setCreditLevel(creditLevel);
        lib.setStatus(status);
        VoResponse voRes =  libService.getServicePageByCondition(lib, pageNum, pageSize, orderBy);
        return voRes;
    }
    
    @GetMapping("results/page")
    public Object getAllResults(@RequestParam("objName") String objName, @RequestParam("checkStatus") String checkStatus, 
            @RequestParam("status") String status,
            @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize,
            @RequestParam(value="orderBy",required=false)  String orderBy) {
        VoQuery lib = new VoQuery();
        lib.setObjName(objName);
        lib.setCheckStatus(checkStatus);
        lib.setStatus(status);
        VoResponse voRes =  libService.getResultsPageByCondition(lib, pageNum, pageSize, orderBy);
        
        return voRes;
    }
    
    @GetMapping("requirement/page")
    public Object getAllRequirement(@RequestParam("objName") String objName, @RequestParam("checkStatus") String checkStatus, 
            @RequestParam("status") String status,
            @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize,
            @RequestParam(value="orderBy",required=false)  String orderBy) {
        VoQuery lib = new VoQuery();
        lib.setObjName(objName);
        lib.setCheckStatus(checkStatus);
        lib.setStatus(status);
        VoResponse voRes =  libService.getRequirementPageByCondition(lib, pageNum, pageSize, orderBy);
        return voRes;
    }
    
    /**
     * 用户 发布需求/成果
     * @param form
     * @return
     */
    @PostMapping("user/publish")
    public VoResponse addReUser(@RequestBody BusUserForm form) {
        VoResponse voRes = new VoResponse();
        if(form.getFormType() != UserTypeEnum.Requirement.key() && form.getFormType() != UserTypeEnum.Results.key()) {
            voRes.setFail(voRes);
            voRes.setMessage("类型错误");
            return voRes;
        }
        if(form.getCheckStatus() != CheckStatusEnum.Draft.value() && form.getCheckStatus() != CheckStatusEnum.Checking.value()) {
            voRes.setFail(voRes);
            voRes.setMessage("状态错误");
            return voRes;
        }
        voRes = libService.publishRe(form);
        return voRes;
    }
    
    /**
     * 管理员 发布需求/成果
     * @param form
     * @return
     */
    @PostMapping("publish")
    public VoResponse addRe(@RequestBody BusUserForm form) {
        VoResponse voRes = new VoResponse();
        if(form.getFormType() != UserTypeEnum.Results.key() && form.getFormType() != UserTypeEnum.Requirement.key()) {
            voRes.setFail(voRes);
            voRes.setMessage("表格类型错误");
            return voRes;
        }
        if(form.getCheckStatus()<-1 || form.getCheckStatus()>2) {
            voRes.setFail(voRes);
            voRes.setMessage("状态错误");
            return voRes;
        }
        voRes = libService.addLib(form);
        return voRes;
    }
    
    /**
     * 文件上传form
     * @param file
     * @return
     */
    @PostMapping("upload")
    public Object upload(@RequestParam("file")MultipartFile file) {
        MyFileUtil util = new MyFileUtil();
        String filePath = tomcatPath + "user/";
        String [] suffixNames = {".jpg", ".jpeg", ".png"};
        VoResponse voRes = util.upload(file, filePath, suffixNames);
        return voRes;
    }
    
    /**
     * 文件上传base64
     * @param strfile
     * @return
     */
    @PostMapping("upload2")
    public Object upload2(@RequestBody String strfile) {
        MyFileUtil util = new MyFileUtil();
        String filePath = tomcatPath + "user/";
        String [] suffixNames = {".jpg", ".jpeg", ".png"};
        VoResponse voRes = util.upload2(strfile, filePath, suffixNames);
        return voRes;
    }
    
    public static void main(String[] args) {
        String  strfile = "data%3Aimage%2Fpng%3Bbase64%2CiVBORw0KGgoAAAANSU";
        try {
            strfile = URLDecoder.decode(strfile, "utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(strfile);
    }
    
    /**
     * 文件下载
     * @param response
     * @param fileName
     * @return
     */
    @GetMapping("/download")
    public Object downloadFile(HttpServletResponse response, @RequestParam("fileName") String fileName) {
        MyFileUtil util = new MyFileUtil();
        String filePath = tomcatPath + "download/";
        VoResponse voRes = util.download(fileName, filePath, response);
        return voRes;
    }
    
    @GetMapping("/exportLib")
    public Object exportLib(HttpServletResponse response,
            @RequestParam(value = "objName", required = false) String objName,
            @RequestParam(value = "checkStatus", required = false) String checkStatus,
            @RequestParam("userType") String userType,
            @RequestParam(value="creditLevel", required=false) String creditLevel,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam("token") String token) throws IOException {
        if (WzStrUtil.isBlank(token)) {
            VoResponse voRes = new VoResponse();
            voRes.setFail(voRes);
            voRes.setMessage("未登录或登录已超时");
            return voRes;
        }
        String mimeType = "application/octet-stream";
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", "lib-export.xls");
        response.setHeader(headerKey, headerValue);
        response.setContentType(mimeType);
        VoQuery query = new VoQuery();
        query.setObjName(objName);
        query.setCheckStatus(checkStatus);
        query.setUserType(userType);
        query.setCreditLevel(creditLevel);
        query.setStatus(status);
        query.setTokenStr(token);
        VoResponse voRes = libService.exportLib(query, response.getOutputStream());
        return voRes;
    }
    
    @PostMapping("importLibExcel")
    public VoResponse importLib(@RequestParam("file")MultipartFile file, @RequestParam("userType") int userType) {

        MyFileUtil util = new MyFileUtil();
        String filePath = tomcatPath + "/excel-lib/";
        String [] suffixNames = {".xlsx", ".xls"};
        VoResponse voRes = util.upload(file, filePath, suffixNames);

        if(voRes.getSuccess()) {
            BusUserForm userform = libService.getUserForm(userType);
            ExcelUtil excel = new ExcelUtil();
            String path = filePath + "/" +voRes.getData();
            JSONArray json = excel.excelTranJson(path, userType, (null == userform ? null : userform.getDetail()));

            voRes = libService.addLibBatch(json, userType);
            util.delFile(path);
        } else {
            return voRes;
        }
        return voRes;
    }


}
